<?php

namespace Lib\PayApi\Rightyoo;
use Lib\Utils\Utils;

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/22
 * Time: 1:36
 */
class PaymentClient {
    public static function pay($orderNo, $money, $pbank) {
        $rightyoo = C('RIGHTYOO');
        $banks = explode('_',$pbank);
		$Md5key = $rightyoo['key'];
	
		// exit(getenv('HTTP_X_FORWARDED_FOR'));
		
		$spbill_create_ip = explode(',',self::get_inter());
        $requestarray = array(
			'app_id'=>$rightyoo['app_id'],
			'mch_id'=>$rightyoo['mch_id'],
			'nonce_str'=>md5(time().mt_rand(0,1000)),
			'pay_channel'=>$rightyoo['tongdao'][$banks[0]][$banks[1]],
			'out_trade_no'=>$orderNo,
			'body'=>$rightyoo['body'],
			'total_fee'=>$money*100,
			'spbill_create_ip'=>$spbill_create_ip[0],//getenv('HTTP_X_FORWARDED_FOR'),//$rightyoo['spbill_create_ip'],//getenv('REMOTE_ADDR'),
			'notify_url'=>$rightyoo['notifyUrl'],
			'trade_type'=>$banks[1],
			'scene_info'=>urlencode($rightyoo['scene_info']),
			'product_id'=>md5(time().mt_rand(0,1000))
        );
		
		// exit(self::get_inter());
		
		ksort($requestarray);
		reset($requestarray);
		
		$md5str = "";
		foreach ($requestarray as $key => $val) {
			$md5str = $md5str . $key . "=" . $val . "&";
		}
		$sign = strtoupper(md5($md5str . "key=" . $Md5key));
		$requestarray['sign'] = $sign;
		
		// $requestarray['scene_info'] = urlencode($rightyoo['scene_info']);
		
		// $json_str = json_encode($requestarray, true);
		// exit($json_str); 
		
		return Utils::post($rightyoo['baseUri'], $requestarray);
    }
	
	private static function get_inter() {
        $onlineip = '';
        if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'), 'unknown')) {
            $onlineip = getenv('HTTP_CLIENT_IP');
        } elseif (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'), 'unknown')) {
            $onlineip = getenv('HTTP_X_FORWARDED_FOR');
        } elseif (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'), 'unknown')) {
            $onlineip = getenv('REMOTE_ADDR');
        } elseif (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], 'unknown')) {
            $onlineip = $_SERVER['REMOTE_ADDR'];
        }
        return $onlineip;
    }
}